/**
 * PowerCam - 悬浮球摄像头录像应用
 * @format
 */

import React, { useState, useEffect, useRef } from 'react';
import {
  StatusBar,
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Image,
  useColorScheme,
  Alert,
  Platform,
  SafeAreaView,
  PermissionsAndroid,
} from 'react-native';
import { Camera, useCameraDevices, CameraDevice, useCameraDevice } from 'react-native-vision-camera';
import { CameraRoll } from '@react-native-camera-roll/camera-roll';
import { WebView } from 'react-native-webview';
import AsyncStorage from '@react-native-async-storage/async-storage';
import NetInfo from '@react-native-community/netinfo';

interface FloatingCameraProps {
  onClose: () => void;
  isRecording: boolean;
  onToggleRecording: () => void;
  cameraRef: React.RefObject<Camera | null>;
}

// 悬浮球摄像头组件
const FloatingCamera: React.FC<FloatingCameraProps> = ({ onClose, isRecording, onToggleRecording, cameraRef }) => {
  const device = useCameraDevice('back');

  console.log('Camera device:', device);

  if (!device) {
    return (
      <View style={styles.floatingCamera}>
        <Text style={styles.errorText}>摄像头不可用</Text>
      </View>
    );
  }

  return (
    <TouchableOpacity style={styles.floatingCamera} onPress={onToggleRecording}>
      <Camera
        ref={cameraRef}
        style={styles.cameraPreview}
        device={device}
        isActive={true}
        video={true}
        audio={true}
      />
      {/* 录像状态指示器 */}
      {isRecording && (
        <View style={styles.recordingIndicator}>
          <View style={styles.recordingDot} />
        </View>
      )}
{/* 隐藏关闭按钮
      <TouchableOpacity style={styles.closeButton} onPress={onClose}>
        <Text style={styles.closeButtonText}>×</Text>
      </TouchableOpacity>
      */}
    </TouchableOpacity>
  );
};

function App() {
  const isDarkMode = useColorScheme() === 'dark';
  const [showFloatingCamera, setShowFloatingCamera] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const cameraRef = useRef<Camera | null>(null);
  const [permissionStatus, setPermissionStatus] = useState<string>('未检查');
  const [isOnline, setIsOnline] = useState(true);
  const [cachedHtml, setCachedHtml] = useState<string | null>(null);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  // 检查当前权限状态
  const checkPermissions = async () => {
    try {
      const cameraPermission = await Camera.getCameraPermissionStatus();
      const microphonePermission = await Camera.getMicrophonePermissionStatus();
      
      console.log('当前权限状态:', {
        camera: cameraPermission,
        microphone: microphonePermission
      });
      
      setPermissionStatus(`摄像头: ${cameraPermission}, 麦克风: ${microphonePermission}`);
    } catch (error) {
      console.error('检查权限失败:', error);
    }
  };

  // 保存缓存内容
  const saveCachedContent = async (html: string) => {
    try {
      await AsyncStorage.setItem('cached_html', html);
      setCachedHtml(html);
      console.log('HTML内容已缓存');
    } catch (error) {
      console.error('缓存HTML内容失败:', error);
    }
  };

  // 加载缓存内容
  const loadCachedContent = async () => {
    try {
      const cached = await AsyncStorage.getItem('cached_html');
      if (cached) {
        setCachedHtml(cached);
      }
    } catch (error) {
      console.error('加载缓存内容失败:', error);
    }
  };

  // 监听网络状态
  useEffect(() => {
    const unsubscribe = NetInfo.addEventListener(state => {
      setIsOnline(state.isConnected ?? true);
      console.log('网络状态:', state.isConnected ? '在线' : '离线');
    });

    return () => unsubscribe();
  }, []);

  // 显示Toast消息
  const showToastMessage = (message: string) => {
    setToastMessage(message);
    setShowToast(true);
    setTimeout(() => {
      setShowToast(false);
    }, 1000);
  };

  // 应用启动时检查权限和加载缓存
  useEffect(() => {
    checkPermissions();
    loadCachedContent();
  }, []);

  // 请求权限
  const requestPermissions = async () => {
    try {
      // 使用react-native-vision-camera的权限请求方法
      const cameraPermission = await Camera.requestCameraPermission();
      const microphonePermission = await Camera.requestMicrophonePermission();

      console.log('权限状态:', {
        camera: cameraPermission,
        microphone: microphonePermission
      });

      if (cameraPermission === 'granted' && microphonePermission === 'granted') {
        // 权限获取成功，更新状态
        setPermissionStatus(`摄像头: ${cameraPermission}, 麦克风: ${microphonePermission}`);
        return true;
      } else {
        Alert.alert(
          '权限不足', 
          `需要以下权限才能使用此功能:\n摄像头: ${cameraPermission}\n麦克风: ${microphonePermission}\n\n请在设置中手动授予权限`
        );
        // 更新权限状态显示
        setPermissionStatus(`摄像头: ${cameraPermission}, 麦克风: ${microphonePermission}`);
        return false;
      }
    } catch (error) {
      console.error('权限请求失败:', error);
      Alert.alert('错误', '权限请求失败，请在设置中手动授予权限');
      return false;
    }
  };

  // 点击React图标的处理函数
  const handleReactIconPress = async () => {
    if (!showFloatingCamera) {
      // 显示悬浮球并开始录像
      const hasPermissions = await requestPermissions();
      if (hasPermissions) {
        setShowFloatingCamera(true);
        // 延迟一秒后自动开始录像
        setTimeout(() => {
          startRecording();
        }, 1000);
      }
    } else {
      // 停止录像并关闭悬浮球
      if (isRecording) {
        await stopRecording();
      }
      setShowFloatingCamera(false);
    }
  };

  // 开始录像
  const startRecording = async () => {
    if (cameraRef.current && !isRecording) {
      try {
        setIsRecording(true);
        await cameraRef.current.startRecording({
          onRecordingFinished: (video: any) => {
            console.log('录像完成:', video);
            saveVideoToGallery(video.path);
          },
          onRecordingError: (error: any) => {
            console.error('录像错误:', error);
            setIsRecording(false);
          },
        });
      } catch (error) {
        console.error('开始录像失败:', error);
        setIsRecording(false);
      }
    }
  };

  // 停止录像
  const stopRecording = async () => {
    if (cameraRef.current && isRecording) {
      try {
        await cameraRef.current.stopRecording();
        setIsRecording(false);
      } catch (error) {
        console.error('停止录像失败:', error);
      }
    }
  };

  // 保存视频到相册
  const saveVideoToGallery = async (videoPath: string) => {
    try {
      await CameraRoll.save(videoPath, { type: 'video' });
      showToastMessage('视频已保存到相册');
    } catch (error) {
      console.error('保存视频失败:', error);
      showToastMessage('保存失败，请检查权限');
    }
  };

  // 切换录像状态
  const toggleRecording = () => {
    if (isRecording) {
      stopRecording();
    } else {
      startRecording();
    }
  };

  return (
    <View style={styles.container}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
      
      {/* 导航栏 */}
      <SafeAreaView style={styles.navigationBar}>
        <View style={styles.navContent}>
          <Text style={styles.navTitle}>QQ新闻</Text>
          <TouchableOpacity 
            style={styles.cameraToggleButton} 
            onPress={() => setShowFloatingCamera(!showFloatingCamera)}
          >
            <Text style={styles.cameraToggleText}>📷</Text>
          </TouchableOpacity>
        </View>
      </SafeAreaView>
      
      {/* WebView */}
      {!isOnline && cachedHtml ? (
        <WebView
          source={{ html: cachedHtml }}
          style={styles.webview}
          startInLoadingState={true}
          renderLoading={() => (
            <View style={styles.loadingContainer}>
              <Text style={styles.loadingText}>加载缓存内容...</Text>
            </View>
          )}
          domStorageEnabled={true}
          javaScriptEnabled={true}
        />
      ) : (
        <WebView
          source={{ uri: 'https://www.qq.com/' }}
          style={styles.webview}
          startInLoadingState={true}
          renderLoading={() => (
            <View style={styles.loadingContainer}>
              <Text style={styles.loadingText}>正在加载...</Text>
            </View>
          )}
          onError={(syntheticEvent) => {
            const { nativeEvent } = syntheticEvent;
            console.warn('WebView error: ', nativeEvent);
            // 如果有缓存内容，在网络错误时显示缓存
            if (cachedHtml) {
              // 这里可以设置一个状态来强制显示缓存内容
            }
          }}
          onLoadEnd={() => {
            // 网页加载完成后，尝试获取HTML内容进行缓存
            // 注意：由于安全限制，直接获取HTML内容可能不可行
            // 这里我们使用WebView的缓存机制
          }}
          cacheEnabled={true}
          domStorageEnabled={true}
          javaScriptEnabled={true}
          injectedJavaScript={`
            // 尝试缓存页面内容
            setTimeout(() => {
              const html = document.documentElement.outerHTML;
              window.ReactNativeWebView.postMessage(JSON.stringify({
                type: 'HTML_CONTENT',
                content: html
              }));
            }, 2000);
            true;
          `}
          onMessage={(event) => {
            try {
              const data = JSON.parse(event.nativeEvent.data);
              if (data.type === 'HTML_CONTENT' && data.content) {
                saveCachedContent(data.content);
              }
            } catch (error) {
              console.error('解析WebView消息失败:', error);
            }
          }}
        />
      )}

      {/* 悬浮球摄像头 */}
      {showFloatingCamera && (
        <FloatingCamera
          onClose={() => setShowFloatingCamera(false)}
          isRecording={isRecording}
          onToggleRecording={toggleRecording}
          cameraRef={cameraRef}
        />
      )}

      {/* Toast消息 */}
      {showToast && (
        <View style={styles.toast}>
          <Text style={styles.toastText}>{toastMessage}</Text>
        </View>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f0f0f0',
  },
  navigationBar: {
    backgroundColor: '#007AFF',
    paddingBottom: 10,
  },
  navContent: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingTop: 10,
  },
  navTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#FFFFFF',
  },
  cameraToggleButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  cameraToggleText: {
    fontSize: 20,
  },
  webview: {
    flex: 1,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f0f0f0',
  },
  loadingText: {
    fontSize: 16,
    color: '#666',
  },
  floatingCamera: {
    position: 'absolute',
    top: Platform.OS === 'ios' ? 120 : 90,
    right: 20,
    width: 30,
    height: 30,
    borderRadius: 15,
    overflow: 'hidden',
    backgroundColor: '#000',
    elevation: 8,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.22,
    shadowRadius: 2.22,
    zIndex: 1000,
  },
  cameraPreview: {
    flex: 1,
  },
  recordButton: {
    position: 'absolute',
    bottom: 1,
    right: 1,
    width: 10,
    height: 10,
    borderRadius: 5,
    backgroundColor: 'rgba(255, 255, 255, 0.8)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  recordingButton: {
    backgroundColor: 'rgba(255, 0, 0, 0.8)',
  },
  recordDot: {
    width: 5,
    height: 5,
    borderRadius: 2.5,
    backgroundColor: '#ff0000',
  },
  recordingDot: {
    backgroundColor: '#ffffff',
  },
  recordingIndicator: {
    position: 'absolute',
    top: 3,
    left: 3,
    width: 6,
    height: 6,
    borderRadius: 3,
    backgroundColor: '#ff0000',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 0.5,
    },
    shadowOpacity: 0.3,
    shadowRadius: 1,
    elevation: 2,
  },
  closeButton: {
    position: 'absolute',
    top: 1,
    right: 1,
    width: 10,
    height: 10,
    borderRadius: 5,
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  closeButtonText: {
    color: '#fff',
    fontSize: 8,
    fontWeight: 'bold',
  },
  toast: {
    position: 'absolute',
    top: 100,
    left: '50%',
    transform: [{ translateX: -75 }],
    backgroundColor: 'rgba(0, 0, 0, 0.8)',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    zIndex: 2000,
  },
  toastText: {
    color: '#fff',
    fontSize: 14,
    textAlign: 'center',
  },
  errorText: {
    color: '#fff',
    fontSize: 10,
    textAlign: 'center',
    padding: 4,
  },
});

export default App;
